
#! /usr/bin/python

import sys
import os
import time
import random
#sys.path.append('..'+os.sep+'trunk')
sys.path.append('../../../')
from spade import *
class Example(Agent.Agent):
    def _setup(self):
        pass
    def _process(self):
	 pass

class VentaBehaviour(Behaviour.Behaviour):
    def __init__(self,unit):
        self.unit=unit
        Behaviour.Behaviour.__init__(self)

    def _process(self):
        m= self._receive(True)
        if m:
            #print m
            if m.getOntology()=="Ventas" or m.getOntology()=="Consulta":
                unidades=int(m.getContent())
                precio=self.myAgent.precio*(1-(0.5*unidades/self.myAgent.divisor))
                ans=ACLMessage.ACLMessage()
                ans.setOntology(m.getOntology())
                ans.setPerformative("inform")
                ans.setSender(self.myAgent.getAID())
                ans.addReceiver(m.getSender())
                ans.setContent(str(precio))
                ans.setConversationId(m.getConversationId())
                self.myAgent.send(ans)
                #print ans
        time.sleep(0.5)



if __name__ == "__main__":
    a="vendedor"
    if len(sys.argv)>1:
        max=int(sys.argv[1])
    else: max=3
    for n in xrange(0,max):
        agent = a+str(n)+"@apolo.dsic.upv.es"
        #agent = "agent@thx1138.dsic.upv.es"
        #agent = "agent@tatooine.dsic.upv.es"
        b = Example(agent,"pasword")
        l=["ProductoA","ProductoB","ProductoC"]
        #aux=["1","2","3"]
        b.producto=l[random.randint(0,2)]
        b.precio=random.randint(1,2000)
        b.divisor=random.randint(50,100)
        b.start()
        #registramos en el DF  el servicion de venta de productos
        dad = DF.DfAgentDescription()
        dad.setAID(b.getAID())
        search = b.searchService(dad)
        if search:
            dad=search[0]
            d = DF.DfAgentDescription()
            d.setAID(b.getAID())
            b.deregisterService(d)
        else:
          dad = DF.DfAgentDescription()
          dad.setAID(b.getAID())
        ds = DF.ServiceDescription()
        ds.setType("Venta")
        ds.setName(b.producto)
        dad.addService(ds)
        res = b.registerService(dad)
        #anyadiendo el comportamiento de venta
        template = Behaviour.ACLTemplate()
        template.setPerformative("request")
        #template.setOntology("Ventas")
        t = Behaviour.MessageTemplate(template)
        b.addBehaviour(VentaBehaviour(b),t)








